package com.amado.course42Socket.tcp.chatSystem;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.CharBuffer;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Set;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @author wangyulong
 * @version 1.5.0
 * @date 2020/3/7 19:00
 */
public class Server {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(8080);
        AtomicLong atomicLong = new AtomicLong(1);
        System.out.println("服务启动成功");
        while (true) {
            Socket socket = serverSocket.accept();
            System.out.printf("客户端连进来\n", atomicLong.get());
            Long currentId = atomicLong.get();
            SocketUtil.putSocket(atomicLong.getAndIncrement(), socket);
            new Thread(()->{
                BufferedReader inputStreamReader = null;
                PrintWriter printwriter = null;
                try {
                    inputStreamReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                    printwriter = new PrintWriter(socket.getOutputStream(), true);
                    printwriter.println("你已经连接到服务器");
                } catch (IOException e) {
                    e.printStackTrace();
                }
                while (true) {
                    String content = null;
                    try {
                        content = inputStreamReader.readLine();
                        System.out.println("进来消息 " + content);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    String[] contentArray = content.split("#");
                    if(contentArray.length==1){
                        printwriter.write("输入格式必须是#");
                        continue;
                    }
                    if (contentArray[0].equals("1")) {
                        //打印返回所有的连接
                        Set<Long> set = SocketUtil.getIdSet();
                        printwriter.println(set.toString()+"当前用户ID = "+currentId);
                    } else if (contentArray[0].equals("2")) {
                        //连接会话
                        OutputStream outputStream= SocketUtil.getOutputStream(Long.valueOf(contentArray[1]));
                        PrintWriter tempPrint = new PrintWriter(outputStream, true);
                        Date date = new Date();
                        String strDateFormat = "yyyy-MM-dd HH:mm:ss";
                        SimpleDateFormat sdf = new SimpleDateFormat(strDateFormat);
                        tempPrint.println(sdf.format(date)+"收到 "+currentId +"的消息:"+contentArray[2]);
                    }
                }
            }).start();
        }
    }
}
